// pages/orderListDetail/index.js
const app = getApp()
import {
  ApiCommentList,
  ApiGetImageReportList,
  ApiGetReportList,

  ApiDoctorImageReportList,
  ApiDoctorReportList,
  ApiDoctorExamineReportDetail
} from '../../pagesDoctor/api/index'
let {
  baseUrl,
  commonUpdate,
  commonUpload
} = app.globalData
Page({

  /**
   * 页面的初始数据
   */
  data: {
    evaluationActive: [],
    dataList: {},
    baseUrl,
    commonUpdate,
    commonUpload,
    patient_picArr: [],
    isDoctor: true,
    activeNames: [],
    activeNamesJ: ['1'],
    commentList: [],
    active: '订单详情',
    steps: [{
        text: '步骤一',
        desc: '描述信息',
      },
      {
        text: '步骤二',
        desc: '描述信息',
      },
      {
        text: '步骤三',
        desc: '描述信息',
      },
      {
        text: '步骤四',
        desc: '描述信息',
      },
    ],
    ImageReportList: [],
    loading: true,
    activeNames: false
  },

  // 预览图片
  /*   scan: function (e) {
      console.log(e)
      var current = e.target.dataset.src;
      wx.previewImage({
        current: current, //当前显示图片的http链接，我这边是把图片转成了base64
        urls: [current] //需要预览的图片http链接列表
      })
    }, */


  onSupplementary(e) {
    this.setData({
      activeNames: e.detail
    })
  },
  //影响报告详情
  // 影像报告详情
  handleImageDetail(e) {
    console.log('eeeeee', e)
    let val = e.currentTarget.dataset.v
    let query = ""
    if (val.WorksheetId) {
      query = 'time'
    } else {
      query = 'image'
    }
    wx.navigateTo({
      url: `/pages/reportInfo/index?${query}=${encodeURIComponent(JSON.stringify(val))}&&isDoctor=${this.data.isDoctor}`,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  //拨打患者电话
  handlePatientPhone(e) {
    let that = this
    that.onSelect(e.currentTarget.dataset.v)
  },

  onSelect(event) {
    const tel = event
    wx.makePhoneCall({
      phoneNumber: tel,
      success: function () {
        console.log("拨号成功！")
      },
      fail: function () {
        console.log("拨号失败！")
      }
    })
  },


  //历史评价详情
  onChangeEva(event) {
    this.setData({
      evaluationActive: event.detail,
    });
  },


  //切换进度
  onChangeActive(e) {
    console.log(e)
    this.setData({
      active: e.detail.title
    })

  },

  //得到护理人员ID
  getCommentList(id) {
    if (this.data.isDoctor) {
      ApiCommentList(id).then(res => {
        let data = res.data
        if (data && data.length > 0) {
          data.forEach(item => {
            item.text = item.created_at;
            item.desc = item.label
          })
        }
        this.setData({
          commentList: data
        })
      })
    }
  },
  onLoad(options) {
    let optionsData = JSON.parse(options.data)
    if (wx.getStorageSync('loginType') == "doctor") {
      this.setData({
        isDoctor: true,
      })
      //获取评价
      this.getCommentList(optionsData.id)
    } else {
      this.setData({
        isDoctor: false,
      })
    }



    setTimeout(() => {
      /*     console.log(optionsData.item.report_type); */
      //影像文件加载
      if (optionsData.item) {
        if (!this.data.isDoctor) {
          if (optionsData.item && optionsData.item.report_type == '影像报告') {
            console.log('this.data.isDoctor', this.data.isDoctor, optionsData.item.report_type)
            ApiGetImageReportList({
              order_id: optionsData.id
            }).then(res => {
              this.setData({
                ImageReportList: res.data,
                loading: false
              })
            }).finally(_ => {
              this.setData({
                loading: false
              })
            })
          }
        } else {
          ApiDoctorImageReportList({
            order_id: optionsData.id
          }).then(res => {
            this.setData({
              ImageReportList: res.data,
              loading: false
            })
          }).finally(_ => {
            this.setData({
              loading: false
            })
          })
        }
        //化验报告
        if (!this.data.isDoctor) {
          if (optionsData.item && optionsData.item.report_type == '化验报告') {
            ApiGetReportList({
              order_id: optionsData.id
            }).then(res => {
              this.setData({
                ImageReportList: res.data
              })
            }).finally(_ => {
              this.setData({
                loading: false
              })
            })
          }
        } else {
          ApiDoctorReportList({
            order_id: optionsData.id
          }).then(res => {
            this.setData({
              ImageReportList: res.data
            })
          }).finally(_ => {
            this.setData({
              loading: false
            })
          })
        }
      }
    }, 1000);
    //判断是否存在流程
    if (optionsData.order_timeline && optionsData.order_timeline.length > 0) {
      optionsData.order_timeline.forEach(item => {
        item.text = item.name;
        item.desc = item.created_at
      })
    }

    let val = []
    if (JSON.parse(options.data).patient_pic) {
      JSON.parse(options.data).patient_pic.split(',').forEach(item => {
        val.push({
          url: item.startsWith('http') ? item : baseUrl + commonUpload + item,
          type: item.match(/\.(\w+)$/) ? item.match(/\.(\w+)$/)[1] : ''
        })
      })
    }
    //价格详情
    if (optionsData.price_detail && optionsData.price_detail.length > 0) {
      optionsData.price_detailCopy = this.forMatterPrice(optionsData.price_detail)
    }
    //耗材详情
    if (optionsData.material_price_detail && optionsData.material_price_detail.length > 0) {
      optionsData.material_price_detailCopy = this.forMatterPrice(optionsData.material_price_detail)
    }
    this.setData({
      dataList: optionsData,
      patient_picArr: val
    })
  },
  //预览图片
  scan: function (e) {
    var current = e.target.dataset.src;
    wx.previewImage({
      current: current, //当前显示图片的http链接，我这边是把图片转成了base64
      urls: [current] //需要预览的图片http链接列表
    })
  },

  materialPriceChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },

  materialPriceChangeJ(event) {
    this.setData({
      activeNamesJ: event.detail,
    });
  },

  forMatterPrice(price_detail) {
    let val = JSON.parse(price_detail);
    let data = [];
    for (const key in val) {
      data.push({
        name: key,
        value: val[key]
      });
    }
    return data
  },

  openView(path) {
    console.log(path)
    wx.openDocument({
      filePath: path.url,
      success: function (res) {

      },
      fail: () => {
        wx.showToast({
          title: '文件打开失败！',
          icon: "error"
        })
      }
    })
  },
  viewFile(e) {
    const url = e.currentTarget.dataset.item.url
    wx.downloadFile({
      url: url,
      header: {},
      success: function (res) {
        var filePath = res.tempFilePath;
        /*  wx.shareFileMessage({
           filePath: filePath,
           success() {},
           fail: console.error,
         }) */
        wx.openDocument({
          filePath: filePath,
          success: function (res) {
            console.log('打开文档成功')
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        })
      },
      fail: function (res) {
        console.log('文件下载失败');
      },
      complete: function (res) {},
    })


  },

  getDoctorDetail(e) {
    let val = JSON.stringify(e.currentTarget.dataset.v)
    wx.navigateTo({
      url: `/pages/doctorDetail/index?data=${val}`,
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})